package com.ice.framework.web.listener;

import com.ice.framework.common.context.CustomerUser;
import com.ice.framework.common.context.RequestContext;
import com.ice.framework.common.context.RequestContextThreadLocal;
import com.ice.framework.common.util.MiscUtil;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

/**
 * 监听所有的servlet请求，从请求头中解析出用户信息。
 *
 * （1）UserInfoContextListener所有servlet请求都会监听到。<br>
 *  可以通过这个监听器，从Feign的请求头中解析出透传过来的信息（用户代码、用户名称）
 *
 * （2）执行顺序的说明：<br>
 *  UserInfoContextListener > Interceptor > RequestBodyAdviceHandler
 * @author wangwei
 * @Date 2024/5/11 11:24
 */
public class UserInfoContextListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent requestEvent) {
        if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
            return;
        }
        HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
        String userCode = request.getHeader(RequestContext.AUTHORIZATION_USERCODE);
        String userName = request.getHeader(RequestContext.AUTHORIZATION_USERNAME);
        CustomerUser user = new CustomerUser(userCode, MiscUtil.decode(userName));
        // 缓存到ThreadLocal中
        RequestContextThreadLocal.setCustomerUser(user);
    }

    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        RequestContextThreadLocal.remove();
    }
}
